package com.iplus.ydkf.ehome.module.home;

import android.graphics.Color;
import android.os.Handler;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.db.chart.model.LineSet;
import com.db.chart.view.AxisController;
import com.db.chart.view.LineChartView;
import com.iplus.ydkf.ehome.R;
import com.iplus.ydkf.ehome.common.net.Callback;
import com.iplus.ydkf.ehome.common.net.JsonParser;
import com.iplus.ydkf.ehome.common.net.JsonRequestBody;
import com.iplus.ydkf.ehome.common.net.NetClient;
import com.iplus.ydkf.ehome.common.views.ColorArcProgressBar;
import com.iplus.ydkf.ehome.config.ConString;
import com.iplus.ydkf.ehome.module.base.BaseActivity;

import java.io.IOException;

import butterknife.Bind;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * Created by lhtde on 2016/6/11.
 */
public class SensorActivity extends BaseActivity {
    @Bind(R.id.bar1)
    ColorArcProgressBar bar;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.tv_sensor_roomname)
    TextView tv_roomname;
    @Bind(R.id.tv_sensor_sensorname)
    TextView tv_sensorname;
    @Bind(R.id.iv_sensor_switch)
    ImageView iv_switch;
    @Bind(R.id.linechart)
    LineChartView chart;
    @Bind(R.id.tv_sensor_sensorstate)
    TextView tv_sensorState;
    private float currentValue;
    private int type;
    private String roomName;
    private String sensorName;
    private String unitTitle;
    private JSONObject jsonObject;
    private boolean isGetValue = true;
    private MaterialDialog dialog;
    private LineSet dataset;

    @OnClick(R.id.iv_sensor_switch)
    public void switchControl() {
        isGetValue = false;
        currentValue = 1 - currentValue;
        RequestBody jsonRequestBody = JsonRequestBody.create().put("123", "1q23").build();
        dialog = new MaterialDialog.Builder(this)
                .content("正在加载...")
                .progress(true, 0)
                .build();
        dialog.show();
        String url = ConString.CLOUD_DEVICE + "/" + jsonObject.getString("deviceid") + "/" + jsonObject
                .getString("commandname") + "/" + (int) currentValue;
        loge(url);
        NetClient.sendPostRequest(url, jsonRequestBody, new Callback<JSONObject>(JsonParser.getInstance()) {
            @Override
            public void onResponse(JSONObject jsonObject) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (dialog != null)
                            dialog.dismiss();
                        isGetValue = true;
                    }
                }, 3000);
                if (jsonObject.getIntValue("errorCode") != 0) {
                    snackbar(jsonObject.getString("errorMsg"));
                    return;
                }
            }

            @Override
            public void onFailure(IOException e) {

            }
        });
        if (currentValue == 0)
            iv_switch.setImageResource(R.drawable.icon_switchon);
        else iv_switch.setImageResource(R.drawable.icon_switchoff);
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_sensor;
    }

    @Override
    public void initView(View view) {
        jsonObject = JSONObject.parseObject(getIntent().getStringExtra("json"));
        logd(jsonObject.toJSONString());
        dataset = new LineSet();
        roomName = getIntent().getStringExtra("roomName");
        unitTitle = jsonObject.getString("title");
        type = getIntent().getIntExtra("type", 0);
        sensorName = getIntent().getStringExtra("cname");
        if (roomName != null)
            tv_roomname.setText(roomName);
        if (unitTitle != null) {
            bar.setIsNeedTitle(true);
            bar.setTitle(unitTitle);
        }
        if (type == 0) {//类型传感器
            bar.setVisibility(View.VISIBLE);
            iv_switch.setVisibility(View.GONE);
        } else {
            bar.setVisibility(View.GONE);
            iv_switch.setVisibility(View.VISIBLE);
        }
        tv_sensorname.setText(sensorName);
        toolbar.setNavigationIcon(R.drawable.icon_back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                                                 @Override
                                                 public void onClick(View v) {
                                                     finish();
                                                 }
                                             }

        );
    }

    @Override
    public void initData(View view) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                while (true) {
                    if (isGetValue) {
                        getCurrentValue();
                    } else {
                    }
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        NetClient.sendGetRequest(ConString.CLOUD_DEVICE + "/getHistory/" + jsonObject.getString("deviceid") + "/" + jsonObject
                .getString("streamname"), new Callback<JSONObject>(JsonParser.getInstance()) {
            @Override
            public void onResponse(JSONObject jsonObject) {
                if (jsonObject.getIntValue("errorCode") == 0) {
                    float max = 0;
                    JSONArray jsonarray = jsonObject.getJSONArray("data").getJSONObject(0).getJSONArray
                            ("datastreams").getJSONObject(0).getJSONArray("datapoints");
                    for (int i = jsonarray.size() - 1; i >= 0; i--) {
                        JSONObject jsonObject1 = jsonarray.getJSONObject(i);
                        float value = Float.valueOf(jsonObject1.getString("value"));
                        if (value > max)
                            max = value;
                        dataset.addPoint(jsonObject1.getString("at"), value);
                    }
                    dataset.setColor(Color.parseColor("#027FFE"));
                    dataset.setThickness(5);
                    chart.setYAxis(false);
                    chart.setXAxis(false);
                    if (max > 5)
                        chart.setStep((int) (max / 10));
                    chart.setXLabels(AxisController.LabelPosition.NONE);
                    chart.addData(dataset);
                    chart.show();
                }
            }

            @Override
            public void onFailure(IOException e) {

            }
        });
    }

    public void getCurrentValue() {
        NetClient.sendGetRequest(ConString.CLOUD_DEVICE + "/" + jsonObject.getString("deviceid") + "/" + jsonObject
                        .getString("streamname"), new Callback<JSONObject>(JsonParser.getInstance()) {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        if (jsonObject.getIntValue("errorCode") == 0) {
                            int state = jsonObject.getJSONArray("data").getJSONObject(0).getIntValue("online");
                            tv_sensorState.setText("设备当前状态：" + (state == 0 ? "离线" : "在线"));
                            currentValue = Float.valueOf(jsonObject.getJSONArray("data").getJSONObject(0).getString
                                    ("current_value"));
                            bar.setMaxValues(currentValue + 40);
                            bar.setCurrentValues(currentValue);
//                            dataset.addPoint(jsonObject.getJSONArray("data").getJSONObject(0).getString
//                                    ("update_at"), currentValue);
//                            chart.updateValues(dataset.size(), new float[]{currentValue});
                            if (type != 0) {
                                if (currentValue == 0)
                                    iv_switch.setImageResource(R.drawable.icon_switchon);
                                else iv_switch.setImageResource(R.drawable.icon_switchoff);
                            }
                        }
                    }

                    @Override
                    public void onFailure(IOException e) {

                    }
                }

        );
    }

    @Override
    public String getFragmentName() {
        return null;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isGetValue = false;
    }
}
